package cn.tedu.baidashi.service.Impl;


import cn.tedu.baidashi.mapper.UserMapper;
import cn.tedu.baidashi.model.Permission;
import cn.tedu.baidashi.model.Role;
import cn.tedu.baidashi.model.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;

//将用户对象保存到 spring 容器中
@Component
@Slf4j
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.debug("{}",username);
        User user = userMapper.findUserByUsername(username);
        if(user==null){
            return null;
        }

        List<Permission> permissions = userMapper.findUserPermissionsById(user.getId());
        System.out.println(permissions);
        String[] auth = new String[permissions.size()];
        int i=0;
        for (Permission permission : permissions) {
            auth[i] = permission.getName();
            i++;
        }
        List<Role> roles = userMapper.findUserRolesById(user.getId());
        auth = Arrays.copyOf(auth,auth.length+roles.size());
        for (Role role : roles) {
            auth[i] = role.getName();
            i++;
        }

        UserDetails details = org.springframework.security.core.userdetails.User.builder()
                                    .username(user.getUsername())
                                    .password(user.getPassword())
                                    .authorities(auth)
                                    .accountLocked(user.getLocked()==1)
                                    .disabled(user.getEnabled()==0)
                                    .build();
        log.debug("用户信息：{}",details);
        return details;
    }
}
